package com.zmyuan.demo.netty.common;

import com.zmyuan.demo.netty.annotation.MsgAPI;
import com.zmyuan.demo.netty.annotation.RequestMapping;
import com.zmyuan.demo.netty.entity.MethodBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 收集请求命令与对应的执行方法的映射关系
 *
 * Created by zhudebin on 2017/2/14.
 */
@Component
public class MappingInfoApplicationListener implements ApplicationListener<ContextRefreshedEvent>,
        Ordered {
    @Override public void onApplicationEvent(ContextRefreshedEvent event) {

        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(MsgAPI.class);

        for(Map.Entry<String, Object> entry : beans.entrySet()) {

            Method[] methods = entry.getValue().getClass().getMethods();
            for(Method m : methods) {
                RequestMapping rm = m.getDeclaredAnnotation(RequestMapping.class);
                if(rm != null) {
                    Constants.MAPPING_INFO.put(rm.cmd(), new MethodBean(entry.getValue(),m));
                }
            }

        }

        System.out.println(Constants.MAPPING_INFO.size());
    }

    @Override public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
